package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.bean.BeanUtils;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.domain.Product;
import com.spzx.product.api.domain.ProductDetails;
import com.spzx.product.api.domain.ProductSku;
import com.spzx.product.api.domain.vo.SkuLockVo;
import com.spzx.product.api.domain.vo.SkuPrice;
import com.spzx.product.api.domain.vo.SkuQuery;
import com.spzx.product.api.domain.vo.SkuStockVo;
import com.spzx.product.domain.SkuStock;
import com.spzx.product.mapper.ProductDetailsMapper;
import com.spzx.product.mapper.ProductMapper;
import com.spzx.product.mapper.ProductSkuMapper;
import com.spzx.product.mapper.SkuStockMapper;
import com.spzx.product.service.IProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 商品Service业务层处理
 */
@Slf4j
@Service
@Transactional
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductSkuMapper productSkuMapper;

    @Autowired
    private ProductDetailsMapper productDetailsMapper;

    @Autowired
    private SkuStockMapper skuStockMapper;

    @Autowired
    private RemoteProductService remoteProductService;

    //@Autowired
    //private StringRedisTemplate stringRedisTemplate; //适合 key和value都是字符串类型

    @Autowired
    private RedisTemplate redisTemplate; //适合值是任意类型

    /**
     * 查询商品列表
     *
     * @param product 商品
     * @return 商品
     */
    @Override
    public List<Product> selectProductList(Product product) {
        return productMapper.selectProductList(product);
    }

    //原子性
    @Override
    public int insertProduct(Product product) {
        //1.保存Product对象到product表
        productMapper.insert(product); //主键回填

        //2.保存List<ProductSku>对象到product_sku表
        List<ProductSku> productSkuList = product.getProductSkuList();
        if (CollectionUtils.isEmpty(productSkuList)) {
            throw new ServiceException("SKU数据为空");
        }
        int size = productSkuList.size();
        for (int i = 0; i < size; i++) {
            ProductSku productSku = productSkuList.get(i);
            productSku.setSkuCode(product.getId() + "_" + i);
            productSku.setSkuName(product.getName() + " " + productSku.getSkuSpec());
            productSku.setProductId(product.getId());
            productSkuMapper.insert(productSku);

            //添加商品库存  //3.保存List<SkuStock>对象到sku_stock表
            SkuStock skuStock = new SkuStock();
            skuStock.setSkuId(productSku.getId());
            skuStock.setTotalNum(productSku.getStockNum());
            skuStock.setLockNum(0);
            skuStock.setAvailableNum(productSku.getStockNum());
            skuStock.setSaleNum(0);
            skuStockMapper.insert(skuStock);
        }

        //4.保存ProductDetails对象到product_details表
        ProductDetails productDetails = new ProductDetails();
        productDetails.setImageUrls(String.join(",", product.getDetailsImageUrlList()));
        productDetails.setProductId(product.getId());
        productDetailsMapper.insert(productDetails);

        return 1;
    }


    @Override
    public Product selectProductById(Long id) {
        //1.根据id查询Product对象
        Product product = productMapper.selectById(id);

        //2.封装扩展字段：查询商品对应多个List<ProductSku>
        //select * from product_sku where product_id =?
        List<ProductSku> productSkuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, id));
        List<Long> productSkuIdList = productSkuList.stream().map(productSku -> productSku.getId()).toList();


        // select * from sku_stock where sku_id in (1,2,3,4,5,6)
        List<SkuStock> skuStockList = skuStockMapper.selectList(new LambdaQueryWrapper<SkuStock>().in(SkuStock::getSkuId, productSkuIdList));

        Map<Long, Integer> skuIdToTatalNumMap = skuStockList.stream().collect(Collectors.toMap(SkuStock::getSkuId, SkuStock::getTotalNum));
        productSkuList.forEach(productSku -> {
            //返回ProductSku对象，携带了库存数据；
            productSku.setStockNum(skuIdToTatalNumMap.get(productSku.getId()));
        });

        product.setProductSkuList(productSkuList);

        //3.封装扩展字段：商品详情图片List<String>
        ProductDetails productDetails = productDetailsMapper.selectOne(new LambdaQueryWrapper<ProductDetails>().eq(ProductDetails::getProductId, id));
        String imageUrls = productDetails.getImageUrls();   //url,url,url
        String[] urls = imageUrls.split(",");
        product.setDetailsImageUrlList(Arrays.asList(urls));
        //返回Product对象
        return product;
    }


    @Override
    public int updateProduct(Product product) {
        //1.更新Product
        productMapper.updateById(product);

        //2.更新SKU   List<ProductSku>
        List<ProductSku> productSkuList = product.getProductSkuList();
        if (CollectionUtils.isEmpty(productSkuList)) {
            throw new ServiceException("SKU数据为空");
        }
        productSkuList.forEach(productSku -> {
            productSkuMapper.updateById(productSku);

            //3.更新库存   List<ProductSku> -> 获取扩展字段stockNum
            SkuStock skuStock = skuStockMapper.selectOne(new LambdaQueryWrapper<SkuStock>().eq(SkuStock::getSkuId, productSku.getId()));
            skuStock.setTotalNum(productSku.getStockNum());
            skuStock.setAvailableNum(skuStock.getTotalNum() - skuStock.getLockNum());
            skuStockMapper.updateById(skuStock);
        });

        //4.更新详情ProductDetails
        ProductDetails productDetails = productDetailsMapper
                .selectOne(new LambdaQueryWrapper<ProductDetails>().eq(ProductDetails::getProductId, product.getId()));
        productDetails.setImageUrls(String.join(",", product.getDetailsImageUrlList()));
        productDetailsMapper.updateById(productDetails);

        return 1;
    }


    @Override
    public int deleteProductByIds(Long[] ids) {
        //1.删除Product表数据
        // delete from product where id in (1,2)
        productMapper.deleteBatchIds(Arrays.asList(ids));

        //2.删除ProductSku表数据
        List<ProductSku> productSkuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().in(ProductSku::getProductId, Arrays.asList(ids)));
        List<Long> productSkuIdList = productSkuList.stream().map(ProductSku::getId).toList();
        productSkuMapper.deleteBatchIds(productSkuIdList);

        //3.删除SkuStock表数据
        skuStockMapper.delete(new LambdaQueryWrapper<SkuStock>().in(SkuStock::getSkuId, productSkuIdList));

        //4.删除ProductDetails表数据
        // delete from product_details where product_id in (1,2)
        productDetailsMapper.delete(new LambdaQueryWrapper<ProductDetails>().in(ProductDetails::getProductId, Arrays.asList(ids)));
        return 1;
    }


    @Override
    public void updateAuditStatus(Long id, Integer auditStatus) {
        Product product = new Product();
        product.setId(id);
        if (auditStatus == 1) {
            product.setAuditStatus(1);
            product.setAuditMessage("审批通过");
        } else {
            product.setAuditStatus(-1);
            product.setAuditMessage("审批拒绝");
        }
        productMapper.updateById(product);
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        Product product = new Product();
        ProductSku productSku=new ProductSku();
        product.setId(id);
        if (status == 1) {
            product.setStatus(1);
            productSku.setStatus(1);
            productMapper.updateById(product);
            productSkuMapper.update(productSku,new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId,id));
            //上架商品skuId往bitmap中,解决缓存穿透问题
            List<ProductSku> skuList=productSkuMapper
                    .selectList(new LambdaQueryWrapper<ProductSku>()
                            .eq(ProductSku::getProductId,id)
                            .eq(ProductSku::getStatus,1)
                            .select(ProductSku::getId));
            if (!CollectionUtils.isEmpty(skuList)){
                String key="sku:product:data";
                for (ProductSku sku : skuList) {
                    Long skuId = sku.getId();
                    redisTemplate.opsForValue().setBit(key,skuId,true);
                }
            }
        } else {
            product.setStatus(-1);
            productSku.setStatus(-1);
            productMapper.updateById(product);
            productSkuMapper.update(productSku,new LambdaQueryWrapper<ProductSku>()
                    .eq(ProductSku::getProductId,id));
            List<ProductSku> skuList=productSkuMapper
                    .selectList(new LambdaQueryWrapper<ProductSku>()
                            .eq(ProductSku::getProductId,id)
                            .eq(ProductSku::getStatus,-1)
                            .select(ProductSku::getId));
            if (!CollectionUtils.isEmpty(skuList)){
                String key="sku:product:data";
                for (ProductSku sku : skuList) {
                    Long skuId = sku.getId();
                    redisTemplate.opsForValue().setBit(key,skuId,false);
                }
            }
        }
        productMapper.updateById(product);
    }


    @Override
    public List<ProductSku> getTopSale() {
        return productSkuMapper.getTopSale();
    }


    @Override
    public List<ProductSku> skuList(SkuQuery skuQuery) {
        return productSkuMapper.skuList(skuQuery);
    }


    /**
     * 服务提供者：6个接口来服务于商品详情查询。需要进行优化，提供查询效率。
     * 需要使用redis来提高性能。
     */

    @Override
    public ProductSku getProductSku(Long skuId) {
        //1.从缓存里面查数据,有则返回
        String dataKey="product:sku:"+skuId;
        ProductSku productSku =(ProductSku) redisTemplate.opsForValue().get(dataKey);
        if (redisTemplate.hasKey(dataKey)){
            log.info("from redis productSku="+productSku);
            return productSku;
        }
        //2.缓存没有 从数据库中获取 获取后放到缓存区 下次利用提高数据
        //第一次查询这个数据 或 缓存失败
        String lockKey="product:sku:lock:"+skuId;
        String uuid=UUID.randomUUID().toString().replaceAll("-","");
        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(lockKey, uuid, 5, TimeUnit.SECONDS);
        if (ifAbsent){
            //增加分布式锁 只放行一个请求获取数据库数据
            try {
                productSku=getProductSkuFromDb(skuId);//数据库没有数据 null
                int ttl=productSku==null?60:600;//数据库不存在的数据缓存1分钟 数据库存在的数据缓存10分钟
                redisTemplate.opsForValue().set(dataKey,productSku,ttl,TimeUnit.SECONDS);//存储属性值都是空的对象
                return productSku;
            } finally {
                //释放分布式锁代码放在finally 中把锁释放 避免死锁
                String script="if redis.call('get',KEYS[1])==ARGV[1]\n" +
                        "then\n" +
                        "return redis.call('del',KEYS[1])\n" +
                        "else\n" +
                        "return 0\n" +
                        "end;";
                DefaultRedisScript<Long> redisScript=new DefaultRedisScript<>(script, Long.class);
                Long result =(Long) redisTemplate.execute(redisScript,
                        Arrays.asList(lockKey)//KEYS[1]
                        , uuid//ARGV[1]
                );
                log.info("DefaultRedisScript-result="+result);
            }
        }else {
            //睡觉+自旋
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {}
            return this.getProductSku(skuId);
        }
    }
    @Transactional(readOnly = true ,timeout = 3)
    protected ProductSku getProductSkuFromDb(Long skuId){
        return productSkuMapper.selectById(skuId);
    }


    @Override
    public Product getProduct(Long id) {
        return productMapper.selectById(id);
    }


    @Override
    public SkuPrice getSkuPrice(Long skuId) {
        ProductSku productSku = productSkuMapper.selectOne(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getId, skuId).select(ProductSku::getSalePrice, ProductSku::getMarketPrice));
        SkuPrice skuPrice = new SkuPrice();
        BeanUtils.copyProperties(productSku, skuPrice);
        return skuPrice;
    }


    @Override
    public ProductDetails getProductDetails(Long id) {
        return productDetailsMapper.selectOne(new LambdaQueryWrapper<ProductDetails>().eq(ProductDetails::getProductId, id));
    }


    @Override
    public Map<String, Long> getSkuSpecValue(Long id) {
        List<ProductSku> productSkuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, id).select(ProductSku::getId, ProductSku::getSkuSpec));
        Map<String, Long> skuSpecValueMap = new HashMap<>();
        productSkuList.forEach(item -> {
            skuSpecValueMap.put(item.getSkuSpec(), item.getId());
        });
        return skuSpecValueMap;
    }


    @Override
    public SkuStockVo getSkuStock(Long skuId) {
        SkuStock skuStock = skuStockMapper.selectOne(new LambdaQueryWrapper<SkuStock>().eq(SkuStock::getSkuId, skuId));
        SkuStockVo skuStockVo = new SkuStockVo();
        BeanUtils.copyProperties(skuStock, skuStockVo);
        return skuStockVo;
    }


    // select * from product_sku where id in (1,2,3)
    // select id,sale_price,market_price from product_sku where id in (1,2,3)
    @Override
    public List<SkuPrice> getSkuPriceList(List<Long> skuIdList) {
        if (CollectionUtils.isEmpty(skuIdList)) {
            return new ArrayList<SkuPrice>();
        }
        List<ProductSku> skuList = productSkuMapper
                .selectList(new LambdaQueryWrapper<ProductSku>().in(ProductSku::getId, skuIdList)
                        .select(ProductSku::getId, ProductSku::getSalePrice, ProductSku::getMarketPrice));
        if (CollectionUtils.isEmpty(skuList)) {
            return new ArrayList<SkuPrice>();
        }
        return skuList.stream().map((sku) -> {
            SkuPrice skuPrice = new SkuPrice();
            skuPrice.setSkuId(sku.getId());
            skuPrice.setSalePrice(sku.getSalePrice());
            skuPrice.setMarketPrice(sku.getMarketPrice());
            return skuPrice;
        }).toList();
    }

    @Transactional
    @Override
    public String checkAndLock(String orderNo, List<SkuLockVo> skuLockVoList) {
        //去重
        String key="sku:checkAndLock:"+orderNo;
        String dataKey="sku:lock:data:"+orderNo;
        //加分布式锁
        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(key, orderNo, 1, TimeUnit.HOURS);
        if (!ifAbsent){//加锁不成功
         if (redisTemplate.hasKey(dataKey)){
             return "";
         }
         return "重复调用";
        }
        //检查库存
        for (SkuLockVo skuLockVo : skuLockVoList) {
            SkuStock skuStock = skuStockMapper.check(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
            if (skuStock==null){
                skuLockVo.setIsHaveStock(false);
            }else {
                skuLockVo.setIsHaveStock(true);
            }
        }
        //库存不够
        if (skuLockVoList.stream().anyMatch((skuStock)->!skuStock.getIsHaveStock())){
            StringBuilder noHaveStockSkuStr=new StringBuilder();
            List<SkuLockVo> noHaveStockSkuLockList = skuLockVoList.stream().filter(item -> !item.getIsHaveStock()).collect(Collectors.toList());
            for (SkuLockVo skuLockVo : noHaveStockSkuLockList) {
                R<ProductSku> product = remoteProductService.getProductSku(skuLockVo.getSkuId(), SecurityConstants.INNER);
                ProductSku productData = product.getData();
                noHaveStockSkuStr.append("["+productData.getSkuName()+"]库存不够");
            }
            redisTemplate.delete(key);
            return noHaveStockSkuStr.toString();
        }else {//库存够 锁
            for (SkuLockVo skuLockVo : skuLockVoList) {
                int count = skuStockMapper.lock(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
                if (count==0){
                    redisTemplate.delete(key);
                    throw new ServiceException("锁定失败");
                }
            }
        }
        //锁定后 存到缓存中
        redisTemplate.opsForValue().set(dataKey,skuLockVoList);
        return "";
    }

    @Override
    public void unlock(String orderNo) {
        //去重 加锁
        String key="sku:unlock:"+orderNo;
        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(key, orderNo, 1, TimeUnit.HOURS);
        if (!ifAbsent){
            return;
        }
        //加锁成功 为空
        String dataKey="sku:lock:data:"+orderNo;
        List<SkuLockVo> skuLockVoList = (List<SkuLockVo>) redisTemplate.opsForValue().get(dataKey);
        if (CollectionUtils.isEmpty(skuLockVoList)){//已支付
            return;
        }
        //不为空 解库存
        for (SkuLockVo skuLockVo : skuLockVoList) {
            int row = skuStockMapper.unlock(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
            if (row==0){
                redisTemplate.delete(key);
                throw new ServiceException("数据库解锁失败");
            }
        }
        //删除缓存数据
        redisTemplate.delete(dataKey);
    }

    @Override
    public void minus(String orderNo) {
        //去重 加锁
        String key="sku:minus:"+orderNo;
        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(key, orderNo, 1, TimeUnit.HOURS);
        if (!ifAbsent){
            return;
        }
        //为空
        String dataKey="sku:lock:data:"+orderNo;
        List<SkuLockVo> skuLockVoList =(List<SkuLockVo>) redisTemplate.opsForValue().get(dataKey);
        if (CollectionUtils.isEmpty(skuLockVoList)){//解锁库存 删除缓存
            return;
        }
        //不为空 减库存
        for (SkuLockVo skuLockVo : skuLockVoList) {
            int row = skuStockMapper.minus(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
            if (row==0){
                redisTemplate.delete(key);
                throw new ServiceException("减库存失败");
            }
        }
        //删除缓存
        redisTemplate.delete(dataKey);
    }
}